<script setup lang="ts">
import type { ElTree } from 'element-plus-cisdi';
import { LsIcon } from '@lingshu/icon';
import { defineProps, h, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
});

const { t } = useI18n();

interface TreeNode {
  label?: string
  children?: TreeNode[]
  [key: string]: any
}

interface Props {
  data?: TreeNode[]
}

const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree> | null>(null);
const treeData = ref<TreeNode[]>([]);

function clearText() {
  filterText.value = '';
}

defineExpose({
  clearText,
});

watch(
  () => props.data,
  (newVal) => {
    treeData.value = newVal || [];
  },
  { immediate: true },
);

watch(
  () => filterText.value,
  (val: string) => {
    treeRef.value?.filter(val);
  },
);

function filterNode(value: string, data: TreeNode): boolean {
  if (!value) {
    return true;
  }
  return data.label?.indexOf(value) !== -1;
}

const defaultProps = {
  children: 'children',
  label: 'label',
};

const searchIcon = h(LsIcon, {
  'font-family': 'iconfont',
  'value': 'icon-Search',
  'class': 'lst-gray5 text-14px!',
} as any);

const searchPlaceholder = t('roleAuthorization.searchFunction');
</script>

<template>
  <div class="tree-filter-component">
    <ElInput
      v-model="filterText"
      :placeholder="searchPlaceholder"
      clearable
      class="no-prefix-space"
      :suffix-icon="searchIcon"
    />

    <ElTree
      ref="treeRef"
      class="filter-tree"
      :data="treeData"
      :props="defaultProps"
      default-expand-all
      :filter-node-method="filterNode"
    >
      <template #empty>
        <ElEmpty />
      </template>
    </ElTree>
  </div>
</template>

<style scoped>
.no-prefix-space:deep(.el-input__prefix) {
  display: none;
}

.no-prefix-space:deep(.el-input__inner) {
  padding-left: 0;
}

.tree-filter-component {
  width: 100%;
}
</style>
